package com.xique.auth.controller;

import com.xique.auth.api.IWxAppApi;
import com.xique.auth.form.AppLoginBody;
import com.xique.auth.form.LoginBody;
import com.xique.auth.service.AppLoginService;
import com.xique.auth.service.ParkMiniLoginService;
import com.xique.auth.service.SysLoginService;
import com.xique.common.core.constant.AppTypeConstants;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.security.service.AppTokenService;
import com.xique.common.security.service.AppTokenServiceV2;
import com.xique.common.security.service.ParkMiniTokenService;
import com.xique.door.api.model.LoginAppUser;
import com.xique.park.api.dto.AppLoginBodyDTO;
import com.xique.park.api.model.LoginParkMiniUser;
import com.xique.sys.api.model.LoginUser;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * token 控制
 * 手机移动端登录（暂时不需要验证码）
 * @author xique
 */
@RestController
@RequestMapping("app")
@ApiModel
@Slf4j
public class AppTokenController
{
    @Autowired
    private AppTokenService appTokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private AppLoginService appLoginService;

    @Autowired
    private AppTokenServiceV2 appTokenServiceV2;

    @Autowired
    private IWxAppApi wxAppApi;

    @PostMapping("/login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        Map<String, Object> params = new HashMap<>();
        params.put("username",form.getUsername());
        params.put("password",form.getPassword());
        AjaxResult result = wxAppApi.appLogin(params);
        log.info("登录返回结果：{}",result);
        if(AjaxResult.isError(result)){
            return R.fail(Integer.parseInt(result.get("code").toString()),result.get("msg").toString());
        }
        LoginUser loginUser = new LoginUser();
        Map<String,Object> userObj = (HashMap) result.get("data");
        loginUser.setParkId(Long.valueOf((Integer) userObj.get("parkId")));
        loginUser.setParkName((String)userObj.get("parkName"));
        loginUser.setToken((String)userObj.get("token"));
        loginUser.setUsername((String)userObj.get("userName"));
        loginUser.setUserid(Long.valueOf((Integer)userObj.get("userId")));
        loginUser.setUserName((String)userObj.get("userName"));
        loginUser.setUserId(Long.valueOf((Integer)userObj.get("userId")));
        // 获取登录token
        return R.ok(appTokenService.createToken(loginUser));
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        LoginUser loginUser = appTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            appTokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = appTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            appTokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    /** ================================================================C端登录====================================================== **/

    @PostMapping("/login/v2")
    public R<?> loginV2(@RequestBody LoginBody form) {
        LoginAppUser userInfo = appLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(appTokenServiceV2.createToken(userInfo));
    }

    @DeleteMapping("logout/v2")
    public R<?> logoutV2(HttpServletRequest request)
    {
        LoginAppUser loginUser = appTokenServiceV2.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUserName();
            // 删除用户缓存记录
            appTokenServiceV2.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            appLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh/v2")
    public R<?> refreshV2(HttpServletRequest request)
    {
        LoginAppUser loginUser = appTokenServiceV2.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            appTokenServiceV2.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    /** ================================================================C端登录====================================================== **/

    @GetMapping("/getPhone")
    public R<String> getPhone(String code) {
        return R.ok(appLoginService.getPhone(code));
    }

    @PostMapping("/wxLogin")
    public R<?> wxLogin(@RequestBody AppLoginBody form) {
        LoginAppUser userInfo = appLoginService.wxLogin(form);
        // 获取登录token
        return R.ok(appTokenServiceV2.createToken(userInfo));
    }

    @GetMapping("/sendSmsCode")
    public R<String> sendAuthCode(String phone) {
        // 获取登录token
        return R.ok(appLoginService.sendAuthCode(phone));
    }

    @PostMapping("/verificationCode")
    public R<?> verificationCode(@RequestBody AppLoginBody form) {
        LoginAppUser userInfo = appLoginService.verificationCode(form);
        // 获取登录token
        return R.ok(appTokenServiceV2.createToken(userInfo));
    }

    @DeleteMapping("/wxLogout")
    public R<?> wxLogout(HttpServletRequest request)
    {
        LoginAppUser loginUser = appTokenServiceV2.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUser().getCellphone();
            // 删除用户缓存记录
            appTokenServiceV2.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            appLoginService.logout(username);
        }
        return R.ok();
    }

    /* ================================================================ 停车小程序 ===================================================================== **/

    @Autowired
    private ParkMiniLoginService parkMiniLoginService;

    @Autowired
    private ParkMiniTokenService parkMiniTokenService;

    @GetMapping("/park/mini/getPhone")
    public R<String> getParkMiniPhone(String code) {
        return R.ok(parkMiniLoginService.getPhone(code));
    }

    @PostMapping("/park/mini/wxLogin")
    public R<?> wxParkMiniLogin(@RequestBody AppLoginBody form) {
        LoginParkMiniUser userInfo = parkMiniLoginService.wxLogin(form);
        userInfo.setAppType(AppTypeConstants.WECHAT);
        // 获取登录token
        return R.ok(parkMiniTokenService.createToken(userInfo));
    }

    @DeleteMapping("/park/mini/wxLogout")
    public R<?> wxParkMiniLogout(HttpServletRequest request)
    {
        LoginParkMiniUser loginUser = parkMiniTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUser().getUserName();
            // 删除用户缓存记录
            parkMiniTokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            parkMiniLoginService.logout(username);
        }
        return R.ok();
    }

    /**
     * 支付宝登录流程
     */
    @GetMapping("/park/mini/getzfbPhone")
    public R<String> getParkMiniZfbPhone(String jsonStr) {
        return R.ok(parkMiniLoginService.getZfbPhone(jsonStr));
    }

    @PostMapping("/park/mini/zfbLogin")
    public R<?> zfbLogin(@RequestBody AppLoginBodyDTO form) {
        LoginParkMiniUser userInfo = parkMiniLoginService.zfbLogin(form);
        userInfo.setAppType(AppTypeConstants.ALIPAY);
        // 获取登录token
        return R.ok(parkMiniTokenService.createToken(userInfo));
    }

    @PostMapping("/park/mini/zfbLogout")
    public R<?> zfbLogout(HttpServletRequest request) {
        //目前和微信注销一样，先拆分后续拓展
        LoginParkMiniUser loginUser = parkMiniTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUser().getCellphone();
            // 删除用户缓存记录
            parkMiniTokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            parkMiniLoginService.logout(username);
        }
        return R.ok();
    }

    @GetMapping("/park/mini/sendSmsCode")
    public R<String> parkMiniSendAuthCode(String phone) {
        // 获取登录token
        return R.ok(parkMiniLoginService.sendAuthCode(phone));
    }

    @PostMapping("/park/mini/verificationCode")
    public R<?> parkMiniVerificationCode(@RequestBody AppLoginBody form) {
        LoginParkMiniUser userInfo = parkMiniLoginService.verificationCode(form);
        // 获取登录token
        return R.ok(parkMiniTokenService.createToken(userInfo));
    }
}
